<template>
	<view class="penrecord_wrap page template-page">
		<view class="content">
			<view class="form-wrapper flex_1 left-page">
				<u-form :model="formData" ref="uForm" :border-bottom="false" :label-width="200" label-align="right">
					<u-form-item label="勘验次数：" prop="time" :border-bottom="false">
						<u-number-box class="number-box" v-model="formData.time" bg-color="#fff" :min="1" :step="1"></u-number-box>
					</u-form-item>
					<u-form-item label="开始时间：" prop="startTime" :border-bottom="false">
						<FormItemDateTime v-model="formData.startTime" placeholder="请选择 开始时间" @showAfter="showDateTimeAfter('startTime')" />
					</u-form-item>
					<u-form-item label="结束时间：" prop="endTime" :border-bottom="false">
						<FormItemDateTime v-model="formData.endTime" placeholder="请选择 结束时间" @showAfter="showDateTimeAfter('endTime')" />
					</u-form-item>
					<u-form-item label="勘验地点：" prop="address" :border-bottom="false">
						<FormItemText v-if="!isNetworkConnected" v-model="formmatAddressVal" />
						<FormItemMap v-else v-model="formmatAddressVal" />
					</u-form-item>
					<u-form-item label="证据链：" prop="" :border-bottom="false">
						<button @click='showEvidenceChain' style='display: inline-block;margin: 0;' size="mini">显示证据链</button>
					</u-form-item>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">勘验相关</text>
						</view>
						<u-form-item label="人员：" prop="inquestPersons" :border-bottom="false">
							<FormItemLargeSelect v-model="formData.inquestPersons" multiple filterable allowCreate :list="userList" labelText="nickName" valueText="userId" @change="onSelectChange($event, 'inquestPersonsName')" />
						</u-form-item>
						<u-form-item label="气象条件：" prop="inquestWeather" :border-bottom="false">
							<FormItemText v-model="formData.inquestWeather" />
						</u-form-item>
						<u-form-item label="勘验情况：" prop="inquestContent" :border-bottom="false">
							<piaoyiEditor class='Editor' ref='piaoyiEditorInquestRef' :name="'inquest'" :values="formData.inquestContent" @changes="piaoyiEditoSaveContens($event, 'inquest')" :maxlength="9999999" />
						</u-form-item>
					</view>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">环境勘验</text>
						</view>
						<u-form-item label="勘验情况：" prop="environInquestContent" :border-bottom="false">
							<piaoyiEditor class='Editor' ref='piaoyiEditorEnvironInquestRef' :name="'environInquest'" :values="formData.environInquestContent" @changes="piaoyiEditoSaveContens($event, 'environInquest')" :maxlength="9999999" />
						</u-form-item>
					</view>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">初步勘验</text>
						</view>
						<u-form-item label="勘验情况：" prop="firstInquestContent" :border-bottom="false">
							<piaoyiEditor class='Editor' ref='piaoyiEditorFirstInquestRef' :name="'firstInquest'" :values="formData.firstInquestContent" @changes="piaoyiEditoSaveContens($event, 'firstInquest')" :maxlength="9999999" />
						</u-form-item>
					</view>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">细项勘验</text>
						</view>
						<u-form-item label="勘验情况：" prop="secondInquestContent" :border-bottom="false">
							<piaoyiEditor class='Editor' ref='piaoyiEditorSecondInquestRef' :name="'secondInquest'" :values="formData.secondInquestContent" @changes="piaoyiEditoSaveContens($event, 'secondInquest')" :maxlength="9999999" />
						</u-form-item>
					</view>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">专项勘验</text>
						</view>
						<u-form-item label="勘验情况：" prop="threeInquestContent" :border-bottom="false">
							<piaoyiEditor class='Editor' ref='piaoyiEditorThreeInquestRef' :name="'threeInquest'" :values="formData.threeInquestContent" @changes="piaoyiEditoSaveContens($event, 'threeInquest')" :maxlength="9999999" />
						</u-form-item>
					</view>
					<u-form-item label="实验报告：" prop="experimentReport" :border-bottom="false">
						<FileChoose :value="experimentReportFileList" :config="fileChooseConfig" @on-upload="(file) => handleOnUpload(file, 'experiment')" @on-remove="(fileList, index) => handleOnRemove(fileList, index, 'experiment')">
						</FileChoose>
					</u-form-item>
					<u-form-item label="检测报告：" prop="detectionReport" :border-bottom="false">
						<FileChoose :value="detectionReportFileList" :config="fileChooseConfig" @on-upload="(file) => handleOnUpload(file, 'detection')" @on-remove="(fileList, index) => handleOnRemove(fileList, index, 'detection')">
						</FileChoose>
					</u-form-item>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">证明相关</text>
						</view>
						<u-form-item label="勘验负责人：" prop="proveLeaderSign" :border-bottom="false">
							<image class="sign-img" v-show="formData.proveLeaderSign" :src="formData.proveLeaderSign" />
							<text style="color: #1e9fff;width: 60rpx;" @click="startSign('formData', 'proveLeaderSign')">签名</text>
						</u-form-item>
						<u-form-item label="记录人：" prop="proveRecorderSign" :border-bottom="false">
							<image class="sign-img" v-show="formData.proveRecorderSign" :src="formData.proveRecorderSign" />
							<text style="color: #1e9fff;width: 60rpx;" @click="startSign('formData', 'proveRecorderSign')">签名</text>
						</u-form-item>
						<u-form-item label="勘验人：" prop="provePersonSign" :border-bottom="false">
							<image class="sign-img" v-show="formData.provePersonSign" :src="formData.provePersonSign" />
							<text style="color: #1e9fff;width: 60rpx;" @click="startSign('formData', 'provePersonSign')">签名</text>
						</u-form-item>
						<u-form-item label="当事人：" prop="inquestPartyList" :border-bottom="false">
							<view class="party-box">
								<view class="party-add">
									<button class="party-btn" @click="inquestPartyAdd">+</button>
								</view>
								<view class="party-list">
									<view class="party-item" v-for="(item, index) in formData.inquestPartyList" :key="index">
										<view class="party-wrap">
											<u-form-item label="姓名：" prop="proveDoPersonName" :border-bottom="false">
												<view class="party-item-name-box">
													<view class="party-item-name-content">
														<text class="name">{{ item.proveDoPersonName }}</text>
														<image class="sign-img" v-show="item.proveDoPersonNameSign" :src="item.proveDoPersonNameSign" />
														<text class="sign-btn" style="color: #1e9fff;width: 60rpx;" @click="startSign('inquestPartyList', 'proveDoPersonNameSign', index)">签名</text>

													</view>
													<view class="party-item-btns">
														<button v-if="isNetworkConnected" class="party-recognition-btn" type="success" size="mini" @click="uploadIdCardImg(index)">身份证识别</button>
														<uni-icons class='party-delete-btn' @click="inquestPartyDel(index)" type="trash" color='red' size="22"></uni-icons>
													</view>
												</view>
											</u-form-item>
											<u-form-item label="出生日期：" prop="proveDoPersonBirth" :border-bottom="false">
												<FormItemDateTime v-model="item.proveDoPersonBirth" format="yyyy年mm月dd日" valueFormat="yyyy-mm-dd" :dateParams="{
                            year: true,
                            month: true,
                            day: true,
                          }" placeholder="请选择 出生日期" @showAfter="showDateTimeAfter('proveDoPersonBirth')" />
											</u-form-item>
											<u-form-item label="证件号码：" prop="proveDoPersonCardNum" :border-bottom="false">
												<FormItemText v-model="item.proveDoPersonCardNum" type="number" />
											</u-form-item>
											<u-form-item label="单位或住址：" prop="proveDoPersonOrg" :border-bottom="false">
												<FormItemText v-model="item.proveDoPersonOrg" />
											</u-form-item>
										</view>
									</view>
								</view>
							</view>
						</u-form-item>
					</view>
				</u-form>
			</view>
			<InquestTem class="flex_1 template" ref='InquestTemRef' :formData="formData" :pdfDownload="pdfDownload" />
		</view>
		<EvidenceChainTabPopup v-model="show" :params="params" />
		<DownloadBtn v-if="isNetworkConnected" class="download-btn" :pdfDownload="pdfDownload" title="询问笔录" :keyId="params.keyId" :formData="formData" :moduleName="currentModule.moduleName" @saveData="submitFormBackBefore" />
		<FooterBtn class="footer-btn" :pdfDownload="pdfDownload" @submit="submitForm" @cancel="handleCancel" />
	</view>
</template>

<script>
	import config from '@/common/config'
	import eventBus from '@/common/eventBus.js'
	import DataFlow from '@/pagesH5/mixins/DataFlow.js'

	import InquestTem from '@/pagesH5/components/inquiryTemplate/inquestTem.vue'
	import DownloadBtn from '@/pagesH5/components/DownloadBtn'
	import FooterBtn from '@/pagesH5/components/FooterBtn'

	import EvidenceChainTabPopup from './components/evidenceChainTabPopup.vue'

	import FormItemText from '@/pagesH5/components/Form/formItemText.vue'
	import FormItemMap from '@/pagesH5/components/Form/formItemMap.vue'
	import FileChoose from '@/uni_modules/file-choose/components/file-choose/file-choose.vue'
	import FormItemDateTime from '@/pagesH5/components/Form/formItemDateTime.vue'
	import FormItemLargeSelect from '@/pagesH5/components/Form/formItemLargeSelect.vue'
	import piaoyiEditor from '@/uni_modules/piaoyi-editor/piaoyi-editor.vue'

	import {
		findStrIndex,
		checkType
	} from '@/utils/index';
	export default {
		mixins: [DataFlow],
		components: {
			EvidenceChainTabPopup,
			InquestTem,
			DownloadBtn,
			FooterBtn,
			FileChoose,
			FormItemText,
			FormItemMap,
			FormItemDateTime,
			FormItemLargeSelect,
			piaoyiEditor
		},
		data() {
			return {
				focusedField: null,
				fileChooseConfig: {
					size: 20,
					limit: 99,
					title: "",
					headers: this.headers,
					formData: {
						time: 1
					},
					automatic: false,
					fileMediatype: 'file',
					mediaTypeFileType: 'pdf'
				},
				userList: [],
				show: false,
			}
		},
		computed: {
			cardUploadUrl() {
				return config.baseUrl + config.adminPath + '/archives/notice/discern';
			},
			formmatAddressVal: {
				get() {
					if (!this.formData.address) return this.formData.address
					if (!this.isNetworkConnected && checkType(this.formData.address) === 'string') return this.formData.address.split(',')[2]
					if (checkType(this.formData.address) === 'string') {
						return this.formData.address
					} else if (checkType(this.formData.address) === 'array') {
						return this.formData.address.join(',')
					}
				},
				set(val) {
					if (!this.isNetworkConnected) {
						this.formData.address = ',,' + val
					} else {
						this.formData.address = val
					}
				}
			},
			experimentReportFileList: {
				get() {
					if (!this.formData.experimentReport) return []
					let oldlist = this.formData.experimentReport == '' ? [] : this.formData.experimentReport.split(',')
					const request = oldlist.map(url => {
						let fileName = url.match(/\/([^/]+)$/)[1];
						return {
							url: url,
							type: 'pdf',
							name: fileName
						}
					})
					return request
				},
				set(val) {
					this.formData.experimentReport = val.map(file => file.url).join(',')
				}
			},
			detectionReportFileList: {
				get() {
					if (!this.formData.detectionReport) return []
					let oldlist = this.formData.detectionReport == '' ? [] : this.formData.detectionReport.split(',')
					const request = oldlist.map(url => {
						let fileName = url.match(/\/([^/]+)$/)[1];
						return {
							url: url,
							type: 'pdf',
							name: fileName
						}
					})
					return request
				},
				set(val) {
					this.formData.detectionReport = val.map(file => file.url).join(',')
				}
			}
		},
		onShow() {
			eventBus.$on('get-sign-event', (base64, key, signKey, index) => {
				console.log(key, signKey);
				this.$nextTick(() => {
					if (index || index == 0) {
						this.$set(this.formData[key][index], signKey, base64)
						console.log(this.formData[key]);
					} else {
						this.$set(this.formData, signKey, base64)
					}
				})
			})
		},
		methods: {
			showDateTimeAfter(field) {
				this.focusedField = field
			},
			showEvidenceChain() {
				this.show = !this.show
			},
			handleOnUpload(file, key) {
				const keyFileList = `${key}ReportFileList`
				let list = this[keyFileList];
				let resultUrl = file.url.replace('/document/raw:', '')
				console.log(resultUrl);
				list.push({
					...file,
					url: resultUrl
				})
				this[keyFileList] = list
			},
			handleOnRemove(fileList, index, key) {
				const keyFileList = `${key}ReportFileList`
				let newFileList = fileList
				this[keyFileList] = [...newFileList]
			},
			// key 是 要渲染到 右侧的字段
			onSelectChange(params, key) {
				const {
					list,
					value,
					item
				} = params
				console.log(params);
				let or = item.map(item => item.nickName).join(' ');
				if (value) {
					const arr1 = value.split(',');
					const arr2 = item.map(item => item.userId);
					const diff = arr1.filter(id => {
						return !arr2.some(id2 => id2 == id)
					});
					let result = diff.join(',')
					Object.assign(this.formData, {
						[key]: result
					});
				} else {
					Object.assign(this.formData, {
						[key]: ''
					});
				}
			},
			piaoyiEditoSaveContens(e, key) {
				console.log(e);
				const formKey = `${key}Content`
				const formKeyRender = `${key}ContentRender`
				this.$set(this.formData, formKeyRender, e.html)
				this.$set(this.formData, formKey, e.delta)
			},
			startSign(obj, val, index) {
				let obj_ = null
				if (typeof obj === 'string') obj_ = obj
				else if (typeof obj === 'object') obj_ = JSON.stringify(obj)

				let url_ = val ? '../components/signComponent?obj=' + obj_ + '&sign=' + val : '../components/signComponent'

				if (index || index === 0) url_ += '&index=' + index

				uni.navigateTo({
					url: url_
				})
			},
			inquestPartyAdd() {
				const item = {
					proveDoPersonBirth: '',
					proveDoPersonCardNum: '',
					proveDoPersonName: '',
					proveDoPersonNameSign: '',
					proveDoPersonOrg: '',
				}
				this.formData.inquestPartyList.push(item)
			},
			inquestPartyDel(index) {
				this.formData.inquestPartyList.splice(index, 1)
			},
			uploadIdCardImg(index) {
				let _this = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						const tempFilePaths = res.tempFilePaths[0];
						// 图片上传
						const uploadTask = uni.uploadFile({
							url: _this.cardUploadUrl,
							filePath: tempFilePaths,
							name: 'file',
							header: _this.headers,
							success: function(res) {
								_this.handleOnSuccess(JSON.parse(res.data), index)
							},
							fail: function(uploadFileFail) {},
							complete: (res) => {}
						});
					},
					error: function(e) {}
				});
			},
			handleOnSuccess(res, index) {
				if (!res.data.words_result_num) {
					uni.showToast({
						title: '无法识别，请上传清晰的证件照片',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '识别成功',
						icon: 'none'
					});
					const {
						姓名: {
							words: reInquirytorName
						},
						性别: {
							words: reInquirytorSex
						},
						出生: {
							words: reInquirytorBirth
						},
						公民身份号码: {
							words: reInquirytorCardNum
						},
						住址: {
							words: reInquirytorAddressOld
						}
					} = res.data.words_result;
					let day = ''
					if (reInquirytorBirth) day = new Date(`${reInquirytorBirth.slice(0, 4)},${parseInt(reInquirytorBirth.slice(4, 6))},${reInquirytorBirth.slice(6, 8)}`);
					let item = {
						proveDoPersonName: reInquirytorName,
						proveDoPersonBirth: this.$u.timeFormat(day, "y-m-d"),
						proveDoPersonCardNum: reInquirytorCardNum,
						proveDoPersonOrg: reInquirytorAddressOld,
					}
					// this.formData.inquestPartyList[index] = item
					this.$set(this.formData.inquestPartyList, index, item)
				}
				this.loading = false;
			},
			beforeHandleData() {
				const userList = this.vuex_basicData.allUserList || []
				this.userList = userList
			},
			initForm() {
				console.log(this.archivesData);
				const {
					doOrg,
					fireAddress,
					doPerson,
					doPersonName,
					doOtherPerson,
					doOtherPersonName,
					weather
				} = this.archivesData
				const currentTime = this.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss');
				let initForm = {
					title: `${this.$u.timeFormat(new Date(), 'yyyymmddhhMM')}`,
					startTime: currentTime,
					endTime: currentTime,
					address: fireAddress,
					inquestPersons: `${doPerson || ''}${doOtherPerson ? `,${doOtherPerson}` : ''}`,
					inquestPersonsName: ``,
					inquestWeather: weather,
					inquestContent: '',
					inquestContentRender: '',
					inquestContentNum: 0,
					environInquestContent: '',
					environInquestContentNum: 0,
					environInquestContentRender: '',
					firstInquestContent: '',
					firstInquestContentNum: 0,
					firstInquestContentRender: '',
					secondInquestContent: '',
					secondInquestContentNum: 0,
					secondInquestContentRender: '',
					threeInquestContent: '',
					threeInquestContentNum: 0,
					threeInquestContentRender: '',
					proveLeaderSign: '',
					proveRecorderSign: '',
					provePersonSign: '',
					inquestPartyList: [],
					experimentReport: '',
					detectionReport: '',
					createTime: ''
				}
				return initForm
			},
			afterHandleData(data) {
				const editorRefArr = ['inquest', 'environInquest', 'firstInquest', 'secondInquest', 'threeInquest']
				for (let i = 0; i < editorRefArr.length; i++) {
					let name = editorRefArr[i]
					// 首字母大写 匹配
					let Str = name.replace(name[0], name[0].toUpperCase());
					const refName = `piaoyiEditor${Str}Ref`
					const contentName = `${name}Content`
					console.log(refName);
					console.log(contentName);
					if (this.$refs[refName] && data[contentName]) {
						this.$refs[refName].update(data[contentName])
					}
				}
			},
		}
	}
</script>
<style scoped lang="scss">
	.penrecord_wrap {

		&>.content {
			.form-wrapper {
				.Editor {
					box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
					width: 100%;
					max-width: 100%;
					overflow: hidden;
				}

				.form-group {
					&_header {
						width: 100%;
						display: flex;
						align-items: center;
						height: 50px;
						line-height: 50px;
						border-bottom: 2rpx solid #eee;
						margin-bottom: 20rpx;
					}

					&_icon {
						margin-right: 8px;
						font-size: 20px;
						color: #000000d9
					}

					&_text {
						font-size: 16px;
						font-weight: bold;
						color: #000000d9
					}

					.row {
						display: flex;

						.u-form-item {
							flex: 1;
						}
					}
				}

				.party-box {
					width: 100%;

					.party-add {
						display: flex;
						justify-content: flex-end;

						button {
							margin: 0;
							border-radius: 50%;
							width: 60rpx;
							height: 60rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							background-color: #3196fA;
							color: #fff;
						}
					}
				}

				.party-item-name-box {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.u-form-item--left__content {
						height: 100%;
					}

					.party-item-name-content {
						display: flex;
						align-items: center;

						.sign-btn {
							cursor: pointer;
						}
					}

					.party-item-btns {
						height: 100%;
						display: flex;
						align-items: center;

						.party-recognition-btn {
							height: 60rpx;
						}

						.party-delete-btn {
							cursor: pointer;
							margin-left: 10rpx;
						}
					}
				}

			}
		}
	}

	::v-deep .form-wrapper {
		.u-form-item {
			padding: 0 10rpx;
			line-height: 1;

			.u-form-item__body {
				margin-bottom: 36rpx;
				min-height: 68rpx;
				line-height: 1;

				.u-form-item--left {
					align-items: flex-start;

					&__content {
						line-height: 60rpx;
					}
				}

				.u-form-item--right__content {
					height: 100%;

					.u-form-item--right__content__slot {
						height: 100%;

						.form-item_value {
							height: 100%;
							flex: 1;
							display: flex;
							align-items: center;
						}

						.form-item_icon {
							height: 100%;
							width: 50rpx;
							text-align: center;
							color: #c0c4cc;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}

		.number-box {
			width: 100%;
			height: 100%;
			border: 2rpx solid #dcdfe6;
			color: #606266;
			background: #fff;
			border-radius: 8rpx;

			.u-icon-plus,
			.u-icon-minus,
			.u-number-input {
				background-color: #f5f7fa;
			}

			.u-number-input {
				margin: 0;
				flex: 1;
			}

			.u-icon-minus {
				border-radius: 8rpx 0 0 8rpx;
				border-right: 2rpx solid #dcdfe6;
			}

			.u-icon-plus {
				border-radius: 0 8rpx 8rpx 0;
				border-left: 2rpx solid #dcdfe6;
			}
		}
	}
</style>